#include <jni.h>
#include <string>

#include <speex/speex_preprocess.h>
#include <speex/speex_echo.h>
/* Symbol visibility prefix */
#define EXPORT __attribute__((visibility("default")))

#define FIXED_POINT
#define USE_KISS_FFT
#define HAVE_CONFIG_H
#define HEADLEN 44
#define SAMPLE_RATE   (48000)
#define SAMPLES_PER_FRAME  (1024)
#define FRAME_SIZE   (SAMPLES_PER_FRAME * 1000/ SAMPLE_RATE)
#define FRAME_BYTES  (SAMPLES_PER_FRAME)

// 定义回声消除器和其他必要的变量
static SpeexEchoState *echo_state = nullptr;
static SpeexPreprocessState *preprocess_state = nullptr;
static int frame_size = 160; // 根据你的采样率设置

extern "C"
JNIEXPORT jstring JNICALL
Java_ai_tuobot_sdk_util_AudioRecorder_stringFromJNI(JNIEnv *env, jobject thiz) {
    std::string hello = "Hello from C++";

    SpeexPreprocessState *state = speex_preprocess_state_init(1024, SAMPLE_RATE);
    int denoise = 1;
    int noiseSuppress = -25;
    speex_preprocess_ctl(state, SPEEX_PREPROCESS_SET_DENOISE, &denoise);
    speex_preprocess_ctl(state, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &noiseSuppress);

    speex_preprocess_state_destroy(state);
    return env->NewStringUTF(hello.c_str());
}



extern "C" {

    // JNI 方法：初始化回声消除器
    JNIEXPORT void JNICALL
    Java_ai_tuobot_sdk_util_EchoCancellation_init(JNIEnv *env, jobject obj, jint sampleRate, jint frameSize) {
        frame_size = frameSize;
        echo_state = speex_echo_state_init(frame_size, frame_size);
        preprocess_state = speex_preprocess_state_init(frame_size, sampleRate);
        speex_preprocess_ctl(preprocess_state, SPEEX_PREPROCESS_SET_ECHO_STATE, echo_state);
    }

    JNIEXPORT void JNICALL
    Java_ai_tuobot_sdk_util_EchoCancellation_processAudio(JNIEnv *env, jobject /* this */, jshortArray input, jshortArray reference, jshortArray output) {
        jshort *in = env->GetShortArrayElements(input, nullptr);
        jshort *ref = env->GetShortArrayElements(reference, nullptr);
        jshort *out = env->GetShortArrayElements(output, nullptr);

        speex_echo_cancellation(echo_state, in, ref, out);
        speex_preprocess_run(preprocess_state, out);

        env->ReleaseShortArrayElements(input, in, 0);
        env->ReleaseShortArrayElements(reference, ref, 0);
        env->ReleaseShortArrayElements(output, out, 0);
    }

    // JNI 方法：释放资源
    JNIEXPORT void JNICALL
    Java_ai_tuobot_sdk_util_EchoCancellation_cleanup(JNIEnv *env, jobject obj) {
        if (echo_state != nullptr) {
            speex_echo_state_destroy(echo_state);
            echo_state = nullptr;
        }
        if (preprocess_state != nullptr) {
            speex_preprocess_state_destroy(preprocess_state);
            preprocess_state = nullptr;
        }
    }

}